package com.supermap.desktop.theme;

import java.awt.Color;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DecimalFormat;

import javax.naming.spi.DirStateFactory.Result;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.supermap.data.ColorGradientType;
import com.supermap.data.Colors;
import com.supermap.data.Dataset;
import com.supermap.data.DatasetType;
import com.supermap.data.DatasetVector;
import com.supermap.data.FieldInfo;
import com.supermap.data.FieldType;
import com.supermap.data.GeoStyle;
import com.supermap.data.Resources;
import com.supermap.data.SymbolType;
import com.supermap.desktop.Application;
import com.supermap.desktop.CommonToolkit;
import com.supermap.desktop.Interface.IFormMap;
import com.supermap.desktop.mapview.MapViewProperties;
import com.supermap.desktop.properties.CommonProperties;
import com.supermap.desktop.properties.CoreProperties;
import com.supermap.desktop.ui.UICommonToolkit;
import com.supermap.desktop.ui.controls.ColorsComboBox;
import com.supermap.desktop.ui.controls.DialogResult;
import com.supermap.desktop.ui.controls.InternalImageIconFactory;
import com.supermap.desktop.ui.controls.SQLExpressionDialog;
import com.supermap.desktop.ui.controls.SymbolDialog;
import com.supermap.desktop.ui.controls.SymbolPreViewPanel;
import com.supermap.mapping.RangeMode;
import com.supermap.mapping.Theme;
import com.supermap.mapping.ThemeRange;
import com.supermap.mapping.ThemeRangeItem;
import com.supermap.ui.MapControl;

/**
 * 标签分段专题图基本设置界面
 * 
 * @author Administrator
 *
 */
public class ThemeRangeAttributePanel extends ThemeChangePanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel panel;
	private JLabel labelLength;
	private JTextField lengthField;
	private JCheckBox jCheckBoxAllVisible;
	private SymbolPreViewPanel jPanelPreview;
	private JComboBox<String> jComboBoxPrecision;
	private JPanel jPanelToolBar;
	private JButton jButtonTextStyle;
	private JComboBox<String> jComboBoxCaption;
	private JLabel jLabelCaption;
	private JLabel jLabelPrecision;
	private JComboBox<String> jComboBoxRange;
	private JButton jButtonMerge;
	private JButton jButtonSplit;
	private JButton jButtonReverse;
	// private JComboBox<?> m_styleModalComboBox;
	private JLabel jLabelRange;
	private JComboBox<Integer> jComboBoxCount;
	private JComboBox<Colors> jComboBoxColor;
	private JComboBox<String> jComboBoxField;
	private JLabel jLabelCount;
	private JLabel jLabelColor;
	private JLabel jLabelField;
	private JTable table;
	private JScrollPane tableScrollPane;

	// private Workspace m_workspace;
	private String fieldInfo = "";
	private RangeMode rangeMode = RangeMode.EQUALINTERVAL;
	private DatasetVector dataset;
	private double filedCount = 5.0;
	private Object[][] tableData = new Object[3][4];
	private static String[] nameStrings = { MapViewProperties.getString("String_TableTitle_Field"), MapViewProperties.getString("String_TableTitle_Min"),
			MapViewProperties.getString("String_TableTitle_Max"), CoreProperties.getString("String_Caption") };
	private ThemeRange themeRangeField;
	private DefaultTableModel defaultTableModel;
	private String captiontype = "<=X<";
	private String numeric = "#";
	private Dataset[] datasets = new Dataset[1];
	private UniqueValue uniqueValue;
	private SymbolDialog textStyleDialog;
	private SQLExpressionDialog sqlDialog;

	private String recordFieldCount;
	private String recordFieldComboBox;

	/**
	 * Create the frame
	 */
	public ThemeRangeAttributePanel(SymbolPreViewPanel previewPanel, Theme themeRange) {
		super();
		setLayout(null);
		setBounds(0, 0, 525, 325);
		initinalize(previewPanel, themeRange);
	}

	public static String getPanelName() {
		return MapViewProperties.getString("String_PanelTitle_AttributeSet");
	}

	/**
	 * 标签分段专题图初始化
	 * 
	 * @param previewPanel
	 * @param themeLabel
	 */
	private void initinalize(SymbolPreViewPanel previewPanel, Theme themeRange) {
		jPanelPreview = previewPanel;
		datasets[0] = jPanelPreview.getDataset();
		dataset = (DatasetVector) jPanelPreview.getDataset();
		themeRangeField = (ThemeRange) themeRange;
		fieldInfo = themeRangeField.getRangeExpression();
		add(getPreviewPanel());
		add(getTopPanel());
		add(getTableScrollPane());
		add(getToolBarPanel());
		addActionListener();
	}


	/**
	 * 预览面板
	 * 
	 * @return m_previewPanel
	 */
	private SymbolPreViewPanel getPreviewPanel() {
		jPanelPreview.setBounds(0, 130, 250, 200);
		return jPanelPreview;
	}

	/**
	 * 上层面板
	 * 
	 * @return
	 */
	private JPanel getTopPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setBorder(BorderFactory.createTitledBorder(MapViewProperties.getString("String_PanelTitle_BasicSet")));
			panel.setLayout(null);
			panel.setBounds(0, 5, 524, 129);
			panel.add(getCaptionLabel());
			panel.add(getPrecisionLabel());
			panel.add(getColorLabel());
			panel.add(getLengthLabel());
			panel.add(getFieldLabel());
			panel.add(getCountLabel());
			panel.add(getRangeLabel());
			panel.add(getFieldComboBox());
			panel.add(getCountComboBox());
			panel.add(getRangeComboBox());
			panel.add(getLengthTextField());
			panel.add(getColorComboBox());
			panel.add(getPrecisionComboBox());
			panel.add(getCaptionComboBox());
		}
		return panel;
	}

	/**
	 * 段标题格式
	 * 
	 * @return
	 */
	private JLabel getCaptionLabel() {
		if (jLabelCaption == null) {
			jLabelCaption = new JLabel();
			jLabelCaption.setBounds(250, 20, 78, 18);
			jLabelCaption.setText(MapViewProperties.getString("String_FiledFormat"));
		}
		return jLabelCaption;
	}

	/**
	 * 段值精度
	 * 
	 * @return
	 */
	private JLabel getPrecisionLabel() {
		if (jLabelPrecision == null) {
			jLabelPrecision = new JLabel();
			jLabelPrecision.setBounds(250, 45, 65, 20);
			jLabelPrecision.setText(MapViewProperties.getString("String_Label_FieldPrecision"));
		}
		return jLabelPrecision;
	}

	/**
	 * 渐变风格
	 * 
	 * @return
	 */
	private JLabel getColorLabel() {
		if (jLabelColor == null) {
			jLabelColor = new JLabel();
			jLabelColor.setBounds(250, 70, 65, 18);
			jLabelColor.setText(MapViewProperties.getString("String_Label_GradualColor"));
		}
		return jLabelColor;
	}

	/**
	 * 分段表达式
	 * 
	 * @return
	 */
	private JLabel getFieldLabel() {
		if (jLabelField == null) {
			jLabelField = new JLabel();
			jLabelField.setBounds(10, 20, 78, 18);
			jLabelField.setText(MapViewProperties.getString("String_Label_FieldInfo"));
		}
		return jLabelField;
	}

	/**
	 * 距离
	 * 
	 * @return
	 */
	private JLabel getLengthLabel() {
		if (labelLength == null) {
			labelLength = new JLabel();
			labelLength.setBounds(12, 95, 46, 18);
			labelLength.setVisible(false);
			labelLength.setText(MapViewProperties.getString("String_Label_Length"));
		}
		return labelLength;
	}

	/**
	 * 段数
	 * 
	 * @return
	 */
	private JLabel getCountLabel() {
		if (jLabelCount == null) {
			jLabelCount = new JLabel();
			jLabelCount.setBounds(12, 70, 46, 18);
			jLabelCount.setText(MapViewProperties.getString("String_Label_RangeCount"));
		}
		return jLabelCount;
	}

	/**
	 * 分段方法
	 * 
	 * @return
	 */
	private JLabel getRangeLabel() {
		if (jLabelRange == null) {
			jLabelRange = new JLabel();
			jLabelRange.setBounds(10, 45, 66, 18);
			jLabelRange.setText(MapViewProperties.getString("String_Label_RangeMethed"));
		}
		return jLabelRange;
	}

	/**
	 * 字段表达式
	 * 
	 * @return m_fieldComboBox
	 */
	private JComboBox<String> getFieldComboBox() {
		if (jComboBoxField == null) {
			jComboBoxField = new JComboBox<String>();
			jComboBoxField.setEditable(true);
			jComboBoxField.setBounds(95, 20, 150, 20);
			int length = datasets.length;
			for (int i = 0; i < length; i++) {
				DatasetVector dataset = (DatasetVector) datasets[i];
				int count = dataset.getFieldCount();
				for (int j = 0; j < count; j++) {
					FieldInfo fieldInfo = dataset.getFieldInfos().get(j);
					if (fieldInfo.getType() != FieldType.TEXT) {
						String item = dataset.getName() + "." + fieldInfo.getName();
						jComboBoxField.addItem(item);
					}
				}
			}
			jComboBoxField.addItem(MapViewProperties.getString("String_Combobox_Expression"));
		}
		return jComboBoxField;
	}

	/**
	 * 段数
	 * 
	 * @return jComboBoxCount
	 */
	private JComboBox<Integer> getCountComboBox() {
		if (jComboBoxCount == null) {
			jComboBoxCount = new JComboBox<Integer>();
			jComboBoxCount.setEditable(true);
			jComboBoxCount.setBounds(95, 70, 150, 20);
			for (int i = 2; i < 32; i++) {
				jComboBoxCount.addItem(i);
			}
			jComboBoxCount.setSelectedItem(themeRangeField.getCount());
		}
		return jComboBoxCount;
	}

	/**
	 * 分段方法
	 * 
	 * @return m_rangeComboBox
	 */
	private JComboBox<String> getRangeComboBox() {
		if (jComboBoxRange == null) {
			jComboBoxRange = new JComboBox<String>();
			jComboBoxRange.setBounds(95, 45, 150, 20);
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_EqualInterval"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_SquareRoot"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_StdDeviation"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_Logarithm"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_Quantile"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_CustomInterval"));
		}
		return jComboBoxRange;
	}

	/**
	 * 单段长度
	 * 
	 * @return m_lengthField
	 */
	private JTextField getLengthTextField() {
		if (lengthField == null) {
			lengthField = new JTextField();
			lengthField.setBounds(95, 95, 150, 20);
			lengthField.setVisible(false);
			lengthField.setText("1");
		}
		return lengthField;
	}

	/**
	 * 渐变色下拉框
	 * 
	 * @return m_colorComboBox
	 */
	@SuppressWarnings("unchecked")
	private JComboBox<Colors> getColorComboBox() {
		if (jComboBoxColor == null) {
			jComboBoxColor = new ColorsComboBox();
			jComboBoxColor.setBounds(335, 70, 170, 20);
			jComboBoxColor.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					if (e.getStateChange() == ItemEvent.SELECTED) {
						refreshColor();
						refreshTable();
					}
				}
			});
		}
		return jComboBoxColor;
	}

	/**
	 * 精度
	 * 
	 * @return m_precisionComboBox
	 */
	private JComboBox<String> getPrecisionComboBox() {
		if (jComboBoxPrecision == null) {
			jComboBoxPrecision = new JComboBox<String>();
			jComboBoxPrecision.setBounds(335, 45, 170, 20);
			jComboBoxPrecision.addItem("");
			jComboBoxPrecision.addItem("1");
			jComboBoxPrecision.addItem("0.1");
			jComboBoxPrecision.addItem("0.01");
			jComboBoxPrecision.addItem("0.001");
			jComboBoxPrecision.addItem("0.0001");
			jComboBoxPrecision.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					int index = jComboBoxPrecision.getSelectedIndex();
					if (index == 0) {
						numeric = "";
					} else if (index == 1) {
						numeric = "#";
					} else if (index == 2) {
						numeric = "#.0";
					} else if (index == 3) {
						numeric = "#.00";
					} else if (index == 4) {
						numeric = "#.000";
					} else if (index == 5) {
						numeric = "#.0000";
					}
					refreshTable();
				}
			});

		}
		return jComboBoxPrecision;
	}

	/**
	 * 段标题格式
	 * 
	 * @return m_captionComboBox
	 */
	private JComboBox<String> getCaptionComboBox() {
		if (jComboBoxCaption == null) {
			jComboBoxCaption = new JComboBox<String>();
			jComboBoxCaption.setBounds(335, 20, 170, 20);
			jComboBoxCaption.addItem("0<=x<100");
			jComboBoxCaption.addItem("0-100");
			jComboBoxCaption.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					if (jComboBoxCaption.getSelectedIndex() == 0) {
						captiontype = "<=X<";
					} else {
						captiontype = "-";
					}
					refreshTable();
				}
			});
		}
		return jComboBoxCaption;
	}

	/**
	 * 加载表格的带滚动条的面板
	 * 
	 * @return m_tableScrollPane
	 */
	private JScrollPane getTableScrollPane() {
		if (tableScrollPane == null) {
			tableScrollPane = new JScrollPane();
			tableScrollPane.setBounds(250, 159, 274, 166);
			tableScrollPane.setViewportView(getTable());
		}
		return tableScrollPane;
	}

	/**
	 * 表格初始化
	 * 
	 * @return m_table
	 */
	private JTable getTable() {
		if (table == null) {
			defaultTableModel = new DefaultTableModel(getData(), nameStrings);
			table = new JTable(defaultTableModel);
			table.getTableHeader().setReorderingAllowed(false);
			table.setRowSelectionAllowed(true);
			table.setColumnSelectionAllowed(true);
			table.setRowHeight(25);
			refreshTable();
		}
		return table;
	}

	/**
	 * 获取表格需要的数据
	 * 
	 * @return tableData
	 */
	private Object[][] getData() {

		int labelCount = themeRangeField.getCount();
		if (labelCount == 0) {
			return tableData = new Object[0][4];
		}
		tableData = new Object[labelCount][4];
		for (int i = 0; i < labelCount; i++) {
			ThemeRangeItem labelItem = themeRangeField.getItem(i);
			GeoStyle geoStyle = labelItem.getStyle();
			uniqueValue = new UniqueValue();
			uniqueValue.setColor(geoStyle.getFillForeColor());
			uniqueValue.setFlag(labelItem.isVisible());
			tableData[i][0] = uniqueValue;
			tableData[i][1] = new DecimalFormat(numeric).format(labelItem.getStart());
			tableData[i][2] = new DecimalFormat(numeric).format(labelItem.getEnd());
			tableData[i][3] = labelItem.getCaption();
		}
		tableData[0][1] = "Min";
		tableData[0][3] = "Min" + captiontype + themeRangeField.getItem(0).getEnd();
		if (captiontype.contains("<")) {
			tableData[0][3] = "Min" + "<X<" + tableData[0][2];
		}
		int lastLabelCount = labelCount - 1;
		tableData[lastLabelCount][2] = "Max";
		tableData[lastLabelCount][3] = tableData[lastLabelCount][1]
				+ captiontype + "Max";

		return tableData;
	}

	/**
	 * @return
	 */
	private JPanel getToolBarPanel() {
		if (jPanelToolBar == null) {
			jPanelToolBar = new JPanel();
			jPanelToolBar.setBorder(BorderFactory.createLineBorder(Color.blue, 1));
			jPanelToolBar.setLayout(null);
			jPanelToolBar.setBounds(250, 135, 273, 24);
			jPanelToolBar.add(getSplitButton());
			jPanelToolBar.add(getMergeButton());
			jPanelToolBar.add(getGeoStyleButton());
			jPanelToolBar.add(getReverseButton());
			// m_toolBarPanel.add(getComboBox_3());
			jPanelToolBar.add(getAllVisibleCheckBox());
		}
		return jPanelToolBar;
	}

	/**
	 * 工具条上的拆分段按钮
	 * 
	 * @return m_splitButton
	 */
	private JButton getSplitButton() {
		if (jButtonSplit == null) {
			jButtonSplit = new JButton();
			jButtonSplit.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					splitItem();
				}
			});
			jButtonSplit.setBounds(56, 2, 20, 20);
			// button_3.setIcon(new ImageIcon( "/icon/fen.png"));
			jButtonSplit.setMargin(new Insets(0, 0, 0, 0));
			jButtonSplit.setIcon(InternalImageIconFactory.Split);
		}
		return jButtonSplit;
	}

	/**
	 * 拆分
	 */
	private void splitItem() {

		int row = table.getSelectedRow();
		int rowCount = table.getRowCount();
		if (row == 0 || row == rowCount - 1) {
			UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_CantSplit"));
		} else if (row > -1) {

			ThemeRangeItem labelItem = themeRangeField.getItem(row);
			double startValue = labelItem.getStart();
			double endValue = labelItem.getEnd();

			double splitValue = startValue + (endValue - startValue) / 2;
			GeoStyle style1 = labelItem.getStyle();
			String caption1 = startValue + captiontype + splitValue;
			String caption2 = splitValue + captiontype + endValue;
			themeRangeField.split(row, splitValue, style1, caption1, style1, caption2);
			jComboBoxCount.setSelectedIndex(jComboBoxCount.getSelectedIndex() + 1);
			refreshTable();

		} else {
			UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_Split"));
		}

	}

	/**
	 * 工具条上的合并段按钮
	 * 
	 * @return m_mergeButton
	 */
	private JButton getMergeButton() {
		if (jButtonMerge == null) {
			jButtonMerge = new JButton();
			jButtonMerge.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					mergeItem();
				}
			});
			jButtonMerge.setBounds(82, 2, 20, 20);
			jButtonMerge.setMargin(new Insets(0, 0, 0, 0));
			jButtonMerge.setIcon(InternalImageIconFactory.Merge);
		}
		return jButtonMerge;
	}

	/**
	 * 合并段方法
	 */
	private void mergeItem() {

		int[] row = table.getSelectedRows();
		if (row.length > 1) {

			int count = row[row.length - 1] - row[0] + 1;

			if (count < themeRangeField.getCount() - 1) {

				ThemeRangeItem startItem = themeRangeField.getItem(row[0]);
				ThemeRangeItem endItem = themeRangeField.getItem(row[row.length - 1]);
				String caption = startItem.getStart() + captiontype + endItem.getEnd();
				themeRangeField.merge(row[0], count, startItem.getStyle(), caption);
				int reduceCount = count - 1;
				jComboBoxCount.setSelectedIndex(jComboBoxCount.getSelectedIndex() - reduceCount);
				refreshTable();
			} else {
				UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_RquiredTwoField"));
			}
		} else {
			UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_NeedChoseTwo"));
		}

	}

	/**
	 * 工具条上的GeoStyle修改按钮
	 * 
	 * @return jButtonTextStyle
	 */
	private JButton getGeoStyleButton() {
		if (jButtonTextStyle == null) {
			jButtonTextStyle = new JButton();
			jButtonTextStyle.setIcon(InternalImageIconFactory.STYLE);
			jButtonTextStyle.setBounds(27, 2, 20, 20);
			// m_textStyleButton.setText("A");
			jButtonTextStyle.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					styleEdit();
				}
			});
			jButtonTextStyle.setMargin(new Insets(0, 0, 0, 0));
		}
		return jButtonTextStyle;
	}

	/**
	 * GeoStyle修改方法
	 */
	private void styleEdit() {

		// int selectIndex = m_table.getSelectedRow();
		int[] selectIndex = table.getSelectedRows();
		if (selectIndex.length > 0) {
			String name = table.getColumnName(0);
			int width = table.getColumn(name).getWidth();
			int height = table.getTableHeader().getHeight();
			int x = table.getLocationOnScreen().x + width;
			int y = table.getLocationOnScreen().y - height;
			int dialogX = x;
			int dialogY = y;
			textStyleDialog = new SymbolDialog();
			textStyleDialog.setLocation(dialogX, dialogY);
			Resources resources = Application.getActiveApplication().getWorkspace().getResources();
			SymbolType symbolType = null;
			GeoStyle geoStyle = new GeoStyle();
			if (CommonToolkit.DatasetTypeWrap.isPoint(dataset.getType())) {
				symbolType = SymbolType.MARKER;
			} else if (CommonToolkit.DatasetTypeWrap.isLine(dataset.getType())) {
				symbolType = SymbolType.LINE;
			} else if (CommonToolkit.DatasetTypeWrap.isRegion(dataset.getType())) {
				symbolType = SymbolType.FILL;
			}
			DialogResult dialogResult = textStyleDialog.showDialog(resources, geoStyle, symbolType);
			if (dialogResult.equals(DialogResult.OK)) {

				GeoStyle textStyle = textStyleDialog.getStyle();

				for (int i = 0; i < selectIndex.length; i++) {

					themeRangeField.getItem(selectIndex[i]).setStyle(textStyle);
					((UniqueValue) table.getValueAt(selectIndex[i], 0)).setColor(textStyle.getFillForeColor());
				}
				jPanelPreview.refreshPreViewMapControl(themeRangeField);
				table.repaint();

			}

		} else {
			UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_ChooseColumnToSetSymbolStyle"));
		}

	}

	/**
	 * 翻转标签样式
	 * 
	 * @return m_textStyleButton
	 */
	private JButton getTextStyleButton() {
		if (jButtonTextStyle == null) {
			jButtonTextStyle = new JButton();
			jButtonTextStyle.setIcon(InternalImageIconFactory.STYLE);
			jButtonTextStyle.setBounds(27, 2, 20, 20);
			// m_textStyleButton.setText("A");
			jButtonTextStyle.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					styleEdit();
				}
			});
			jButtonTextStyle.setMargin(new Insets(0, 0, 0, 0));
		}
		return jButtonTextStyle;
	}

	/**
	 * @return
	 */
	private JButton getReverseButton() {
		if (jButtonReverse == null) {
			jButtonReverse = new JButton();
			jButtonReverse.setBounds(108, 2, 20, 20);
			jButtonReverse.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					themeRangeField.reverseStyle();
					refreshTable();

				}
			});
			jButtonReverse.setMargin(new Insets(0, 0, 0, 0));
			jButtonReverse.setIcon(InternalImageIconFactory.Rever);
		}
		return jButtonReverse;
	}

	/**
	 * 全部显示的JCheckBox
	 * 
	 * @return m_allVisibleCheckBox
	 */
	private JCheckBox getAllVisibleCheckBox() {
		if (jCheckBoxAllVisible == null) {
			jCheckBoxAllVisible = new JCheckBox();
			jCheckBoxAllVisible.setSelected(true);
			jCheckBoxAllVisible.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					int count = themeRangeField.getCount();
					if (jCheckBoxAllVisible.isSelected()) {
						for (int i = 0; i < count; i++) {
							themeRangeField.getItem(i).setVisible(true);
						}
					} else {
						for (int i = 0; i < count; i++) {
							themeRangeField.getItem(i).setVisible(false);
						}
					}
					refreshTable();
					jPanelPreview.refreshPreViewMapControl(themeRangeField);
				}
			});
			jCheckBoxAllVisible.setBounds(1, 2, 20, 20);
			jCheckBoxAllVisible.setText("");
		}
		return jCheckBoxAllVisible;
	}


	/**
	 * 刷新表格
	 */
	private void refreshTable() {
		int count = themeRangeField.getCount();
		for (int i = 0; i < count; i++) {
			ThemeRangeItem rangeItem = themeRangeField.getItem(i);
			String caption = new DecimalFormat(numeric).format(rangeItem.getStart())
					+ captiontype
					+ new DecimalFormat(numeric).format(rangeItem.getEnd());
			rangeItem.setCaption(caption);
		}
		jPanelPreview.refreshPreViewMapControl(themeRangeField);
		defaultTableModel = new DefaultTableModel(getData(), nameStrings);
		table.setModel(defaultTableModel);
		table.repaint();
		TableColumn viewColumn = table.getColumn(MapViewProperties.getString("String_TableTitle_Field"));
		viewColumn.setPreferredWidth(50);
		viewColumn.setMaxWidth(50);
		viewColumn.setMinWidth(50);
		JPanelRenderer colorRenderer = new JPanelRenderer();
		viewColumn.setCellRenderer(colorRenderer);
		JPanelCellEditorForRange cellEditor = new JPanelCellEditorForRange(dataset);
		cellEditor.addPropertyChangeListener("Color",
				new PropertyChangeListener() {
					public void propertyChange(PropertyChangeEvent evt) {
						int index = table.getSelectedRow();
						GeoStyle textStyle = (GeoStyle) evt.getNewValue();
						themeRangeField.getItem(index).setStyle(textStyle);
						((UniqueValue) table.getValueAt(index, 0)).setColor(textStyle.getFillForeColor());
						jPanelPreview.refreshPreViewMapControl(themeRangeField);
						table.repaint();
					}
				});
		cellEditor.addPropertyChangeListener("Check",
				new PropertyChangeListener() {
					public void propertyChange(PropertyChangeEvent evt) {
						int index = table.getSelectedRow();
						boolean isVisible = (Boolean) evt.getNewValue();
						themeRangeField.getItem(index).setVisible(isVisible);
						refreshTable();
					}
				});

		viewColumn.setCellEditor(cellEditor);

		table.getColumn(MapViewProperties.getString("String_TableTitle_Max")).setPreferredWidth(85);
		// table.getColumn("段值上限").setMaxWidth(100);
		table.getColumn(MapViewProperties.getString("String_TableTitle_Min")).setPreferredWidth(85);
		// table.getColumn("段值下限").setMaxWidth(100);
		table.getColumn(CoreProperties.getString("String_Caption")).setPreferredWidth(150);

		table.getModel().addTableModelListener(new TableModelListener() {

			public void tableChanged(TableModelEvent e) {
				int column = table.getSelectedColumn();
				int lastColumn = table.getColumnCount() - 1;
				if (column == lastColumn) {
					int index = table.getSelectedRow();
					String caption = ((String) table.getValueAt(index, column)).trim();
					if (caption.equals("") || caption.equals(null)) {
						String value = themeRangeField.getItem(index).getCaption();
						table.setValueAt(value, index, column);
					} else {
						themeRangeField.getItem(index).setCaption(caption);
						table.repaint();
					}
				}
			}
		});
	}

	private void refreshByCountComboBox() {
		ThemeRange oldTheme = themeRangeField;

		ThemeRange tempTheme = ThemeRange.makeDefault((DatasetVector) dataset,
				fieldInfo, rangeMode, filedCount,
				ColorGradientType.GREENRED);
		setTheme(tempTheme);
		// 此处用多线程解决专题图实际段数和选择段数不一致问题
		final int count = themeRangeField.getCount();
		if (filedCount != count) {
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					ItemListener[] itemListener = jComboBoxColor.getItemListeners();
					jComboBoxColor.removeItemListener(itemListener[0]);
					JTextField textField = (JTextField) jComboBoxCount.getEditor().getEditorComponent();
					textField.setText(String.valueOf(count));
					jComboBoxColor.addItemListener(itemListener[0]);
				}
			});
		}
		fireThemeChanged(new ThemeChangedEvent(this, themeRangeField, oldTheme));
		refreshColor();
		refreshTable();
	}

	/**
	 * 刷新颜色
	 */
	private void refreshColor() {
		if (jComboBoxColor != null) {
			int colorCount = ((Colors) jComboBoxColor.getSelectedItem()).getCount();
			Colors colors = (Colors) jComboBoxColor.getSelectedItem();
			int rangeCount = themeRangeField.getCount();
			if (rangeCount > 0) {
				float ratio = (1f * colorCount) / (1f * rangeCount);
				if (this.dataset.getType().equals(DatasetType.REGION)) {
					themeRangeField.getItem(0).getStyle().setFillForeColor(colors.get(0));
					themeRangeField.getItem(rangeCount - 1).getStyle().setFillForeColor(colors.get(colorCount - 1));
				} else {
					themeRangeField.getItem(0).getStyle().setLineColor(colors.get(0));
					themeRangeField.getItem(rangeCount - 1).getStyle().setLineColor(colors.get(colorCount - 1));
				}
				for (int i = 1; i < rangeCount - 1; i++) {
					int temp = Math.round(i * ratio);
					if (temp == colorCount) {
						temp--;
					}
					if (this.dataset.getType().equals(DatasetType.REGION)) {
						themeRangeField.getItem(i).getStyle().setFillForeColor(colors.get(temp));
					} else {
						themeRangeField.getItem(i).getStyle().setLineColor(colors.get(temp));
					}
				}
			}
			jPanelPreview.refreshPreViewMapControl(themeRangeField);
		}
	}

	/**
	 * 重新设置专题图
	 */
	protected void setTheme(Theme theme) {
		this.themeRangeField = (ThemeRange) theme;
	}

	/**
	 * 为控件添加响应事件
	 */
	private void addActionListener() {
		setFieldInfo();
		setFieldCount();
		setRangeMode();
		setFieldLength();
		addTableListener();
	}

	/**
	 * 为标签设置字段表达式
	 */
	private void setFieldInfo() {
		// 设置字段表达式
		final int allItems = jComboBoxField.getItemCount();
		final JTextField textField = ((JTextField) jComboBoxField.getEditor().getEditorComponent());
		jComboBoxField.addItemListener(new ItemListener() {
			// 记录上一次非空的theme值
			private ThemeRange themeRange;

			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == ItemEvent.SELECTED) {
					// 判断是否为最后一项“表达式”
					if (jComboBoxField.getSelectedIndex() == jComboBoxField.getItemCount() - 1) {
						sqlDialog = new SQLExpressionDialog();
						DialogResult dialogResult = sqlDialog.showDialog(datasets);
						if (dialogResult == DialogResult.OK) {
							String filter = sqlDialog.getQueryParameter().getAttributeFilter();
							if (filter != null && !filter.trim().equals("")) {
								jComboBoxField.insertItemAt(filter, allItems - 1);
								jComboBoxField.setSelectedIndex(allItems - 1);
							}
						}
					} else {
						fieldInfo = jComboBoxField.getSelectedItem().toString();
						StringBuilder builder = new StringBuilder(fieldInfo);
						fieldInfo = builder.substring(builder.lastIndexOf(".") + 1);
					}
					if (!fieldInfo.equals(null) && !fieldInfo.trim().equals("")) {
						ThemeRange oldTheme = null;
						if (themeRangeField != null) {
							themeRange = themeRangeField;
							oldTheme = themeRangeField;
						} else {
							oldTheme = themeRange;
						}
						Theme tempTheme = ThemeRange.makeDefault(
								(DatasetVector) dataset, fieldInfo,
								rangeMode, filedCount,
								ColorGradientType.GREENRED);
						setTheme(tempTheme);
						if (themeRangeField != null) {
							recordFieldComboBox = textField.getText();
							fireThemeChanged(new ThemeChangedEvent(this, themeRangeField, oldTheme));
						}
					}
					if (themeRangeField != null) {
						themeRangeField.setRangeExpression(jComboBoxField.getSelectedItem().toString());
						refreshColor();
						refreshTable();
					}
				}
			}
		});
		// 控制文本输入内容
		textField.addFocusListener(new FocusListener() {
			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				if (themeRangeField == null && jComboBoxField.getSelectedIndex() != jComboBoxField.getItemCount() - 1) {
					UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_FieldInfoWrong"));
					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							textField.setText(recordFieldComboBox);
							textField.requestFocus();
							textField.selectAll();
						}
					});
				}
			}
		});
	}

	/**
	 * 设置段数
	 */
	private void setFieldCount() {
		final JTextField textField = (JTextField) jComboBoxCount.getEditor().getEditorComponent();
		jComboBoxCount.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				String value = jComboBoxCount.getSelectedItem().toString();
				if ("".equals(value.trim())) {
					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							textField.setText(recordFieldCount);
						}
					});
					return;
				}

				filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
				ThemeRangeAttributePanel.this.refreshByCountComboBox();
			}
		});

		textField.getDocument().addDocumentListener(new DocumentListener() {
			// 添加该变量用于优化
			private boolean isException = false;

			public void changedUpdate(DocumentEvent e) {
			}

			public void insertUpdate(DocumentEvent e) {
				int value = -1;
				try {
					value = Integer.valueOf(textField.getText());
					isException = false;
					// 处理各种情况
					if (value <= 0 || (textField.getText().indexOf("0") == 0
							&& textField.getText().length() > 1 || textField.getText().indexOf("-") == 0)) {
						throw new Exception();
					}
					recordFieldCount = textField.getText();
				} catch (Exception exp) {
					isException = true;
					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							textField.setText(recordFieldCount);
						}
					});
				}
				if (isException == false) {
					filedCount = Integer.valueOf(recordFieldCount);
					ThemeRangeAttributePanel.this.refreshByCountComboBox();
				}
			}

			public void removeUpdate(DocumentEvent e) {
				if (isException == false) {
					if ("".equals(textField.getText())) {
						return;
					}
					if (!textField.getText().equals(recordFieldCount)) {
						recordFieldCount = textField.getText();
					}
					filedCount = Integer.valueOf(recordFieldCount);
					ThemeRangeAttributePanel.this.refreshByCountComboBox();
				}
			}
		});

		textField.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent e) {
				if ("".equals(textField.getText().trim())
						|| (textField.getText().indexOf("0") == 0 && textField
								.getText().length() > 1)) {
					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							textField.setText(recordFieldCount);
						}
					});
				}
			}
		});
	}

	/**
	 * table工具条事件响应
	 */
	private void addTableListener() {
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == 3 && e.getClickCount() == 1) {
					JPopupMenu popupMenu = new JPopupMenu();
					JMenuItem splitItem = new JMenuItem(CommonProperties.getString("String_ToolBar_Split"));
					splitItem.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							splitItem();
						}
					});
					JMenuItem mergeItem = new JMenuItem(CommonProperties.getString("String_ToolBar_Merge"));
					mergeItem.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							mergeItem();
						}
					});
					JMenuItem styleItem = new JMenuItem(CoreProperties.getString("String_ModifyStyle"));
					styleItem.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							styleEdit();
						}
					});
					int count = table.getSelectedRowCount();
					if (count == 0) {
						splitItem.setEnabled(false);
						mergeItem.setEnabled(false);
						styleItem.setEnabled(false);
					} else if (count == 1) {
						splitItem.setEnabled(true);
						mergeItem.setEnabled(false);
						styleItem.setEnabled(true);
					} else {
						splitItem.setEnabled(true);
						mergeItem.setEnabled(true);
						styleItem.setEnabled(true);
					}
					popupMenu.add(splitItem);
					popupMenu.add(mergeItem);
					popupMenu.add(styleItem);
					popupMenu.show(table, e.getX(), e.getY());
				}
			}
		});
	}

	/**
	 * 设置分段模式
	 */
	private void setRangeMode() {
		jComboBoxRange.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Object item = jComboBoxRange.getSelectedItem();
				if (item.equals(MapViewProperties.getString("String_RangeMode_EqualInterval"))) {
					rangeMode = RangeMode.EQUALINTERVAL;
					filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
					if (lengthField.isVisible()) {
						lengthField.setVisible(false);
						labelLength.setVisible(false);
					}
					if (!jComboBoxCount.isVisible()) {
						jComboBoxCount.setVisible(true);
						jLabelCount.setVisible(true);
					}
				} else if (item.equals(MapViewProperties.getString("String_RangeMode_SquareRoot"))) {
					rangeMode = RangeMode.SQUAREROOT;
					filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
					if (lengthField.isVisible()) {
						lengthField.setVisible(false);
						labelLength.setVisible(false);
					}
					if (!jComboBoxCount.isVisible()) {
						jComboBoxCount.setVisible(true);
						jLabelCount.setVisible(true);
					}
				} else if (item.equals(MapViewProperties.getString("String_RangeMode_StdDeviation"))) {
					rangeMode = RangeMode.QUANTILE;
					filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
					if (lengthField.isVisible()) {
						lengthField.setVisible(false);
						labelLength.setVisible(false);
					}
					if (!jComboBoxCount.isVisible()) {
						jComboBoxCount.setVisible(true);
						jLabelCount.setVisible(true);
					}
				} else if (item.equals(MapViewProperties.getString("String_RangeMode_Logarithm"))) {
					rangeMode = RangeMode.LOGARITHM;
					filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
					if (lengthField.isVisible()) {
						lengthField.setVisible(false);
						labelLength.setVisible(false);
					}
					if (!jComboBoxCount.isVisible()) {
						jComboBoxCount.setVisible(true);
						jLabelCount.setVisible(true);
					}
				} else if (item.equals(MapViewProperties.getString("String_RangeMode_Quantile"))) {
					rangeMode = RangeMode.STDDEVIATION;
					jComboBoxCount.setVisible(false);
					jLabelCount.setVisible(false);
					lengthField.setVisible(false);
					labelLength.setVisible(false);
				} else if (item.equals(MapViewProperties.getString("String_RangeMode_CustomInterval"))) {
					rangeMode = RangeMode.CUSTOMINTERVAL;
					filedCount = Double.valueOf(lengthField.getText());
					jComboBoxCount.setVisible(false);
					jLabelCount.setVisible(false);
					lengthField.setVisible(true);
					labelLength.setVisible(true);
				} else {
					jComboBoxCount.setVisible(true);
					jLabelCount.setVisible(true);
					lengthField.setVisible(false);
					labelLength.setVisible(false);
				}
				fieldInfo = (String) jComboBoxField.getSelectedItem();
				ThemeRange oldTheme = themeRangeField;
				Theme tempTheme = ThemeRange.makeDefault(
						(DatasetVector) dataset, fieldInfo,
						rangeMode, filedCount,
						ColorGradientType.GREENRED);
				setTheme(tempTheme);
				fireThemeChanged(new ThemeChangedEvent(this, themeRangeField, oldTheme));
				refreshColor();
				refreshTable();
				jPanelPreview.refreshPreViewMapControl(themeRangeField);
			}
		});
	}

	/**
	 * 设置单段长度
	 */
	private void setFieldLength() {
		lengthField.addCaretListener(new CaretListener() {
			String record = "0";

			public void caretUpdate(CaretEvent e) {
				String field = lengthField.getText();
				if (!field.trim().equals("")) {
					try {
						filedCount = Double.valueOf(field);
						record = field;
						ThemeRange oldTheme = themeRangeField;
						Theme tempTheme = ThemeRange.makeDefault(
								(DatasetVector) dataset, fieldInfo,
								rangeMode, filedCount,
								ColorGradientType.GREENRED);
						setTheme(tempTheme);
						fireThemeChanged(new ThemeChangedEvent(this, themeRangeField, oldTheme));
						if (themeRangeField != null) {
							refreshColor();
							refreshTable();
						}
					} catch (Exception ept) {
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								lengthField.setText(record);
							}
						});
					}
				}
			}
		});
	}

	/**
	 * 返回专题图
	 */
	protected Theme gettheme() {
		return themeRangeField;
	}

}
